/**
 * Class which implements functionality allowing to dynamically load JavaScript files
 *
 * @author Mykhailo Stadnyk <mikhus@gmail.com>
 * @version 1.0
 * @license MIT
 */
Ajax.Loader = Ajax.Class({

	/**
	 * @access private - holds all loaded scripts with this loader
	 */
	_includes : [],

	/**
	 * @access public - base URL from which scripts should be loaded
	 */
	baseUrl  : '',

	/**
	 * Class constructor.
	 * Sets base URL for this loader.
	 *
	 * @param  String base - base URL which should be used with current loader
	 */
	constructor : function( base) {
		if (Ajax.isString( base) && !/^https?:\/\/[-a-z0-9]+(\.[-a-z0-9]+)*\//i.test( base)) {
			throw new TypeError( 'Passed base url is not valid!');
		}
		this.baseUrl = base.replace( /\/?$/, '/');
	},

	/**
	 * Loads given script from base URL and evaluates callback after script load
	 * If passed full URL - loads from it
	 *
	 * @param  String script     - script filename path from base URL
	 * @param  Function callback - function which should be executed after script load 
	 * @return Void
	 */
	include : function( script, callback) {
		var url = this.buildUrl( script);
		if (!(url && this.isLoaded( url))) {
			if (!Ajax.isFunction( callback)) callback = Function.blank;
			var transport = new Ajax.Transport( AJAX_TRANSPORT_TYPE_SCRIPT);
			transport.open( 'GET', url);
			var loader = this;
			transport.onreadystatechange = function() {
				if (this.readyState == -1 || this.readyState == 'loaded') {
					loader.register( url);
					eval( this.responseText);
					callback();
				}
			}
			transport.send( null);
		}
	},

	/**
	 * Builds and returns full URL for passed script filename
	 * If passed full URL - returns itself
	 *
	 * @param  String script - filename of a script to load
	 * @return String - full URL to passed script
	 */
	buildUrl : function( script) {
		if (!script || !Ajax.isString( script)) return; 
		var url = (!/^https?:\/\//i.test( script) ? this.baseUrl + script.replace( /^\/?/, '') : script);
		return url;
	},

	/**
	 * Returns all hold by this loader script includes
	 * 
	 * @returns Array 
	 */
	getIncludes : function() {
		return this._includes;
	},

	/**
	 * Register new loaded script URL
	 *
	 * @param  String script - loaded script
	 * @return Void
	 */
	register : function( script) {
		var url = this.buildUrl( script);
		this.getIncludes().push( url);
	},

	/**
	 * Checks if passed script has been already loaded
	 *
	 * @param  String script - script name to check
	 * @return Boolean 
	 */
	isLoaded : function( script) {
		var url = this.buildUrl( script);
		return this.getIncludes().inArray( url);
	}
});